package per.wsj.stickyheader.decoration;

import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.text.TextUtils;
import android.util.LongSparseArray;
import android.util.SparseArray;
import android.view.View;
import android.view.ViewGroup;
import androidx.recyclerview.widget.RecyclerView;


public class SectionDecoration extends RecyclerView.ItemDecoration {

    private final SparseArray<Rect> mHeaderRects = new SparseArray<>();
    private final LongSparseArray<View> mHeaderViews = new LongSparseArray<>();

    private PowerGroupListener mGroupListener;
    /**
     * 悬浮栏高度
     */
    private int mGroupHeight = 80;

    public SectionDecoration(PowerGroupListener groupListener) {
        this.mGroupListener = groupListener;
    }


    @Override
    public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
        super.getItemOffsets(outRect, view, parent, state);
        int pos = parent.getChildAdapterPosition(view);
        String groupId = getGroupName(pos);
        if (groupId == null) {
            return;
        }
        //只有是同一组的第一个才显示悬浮栏
        if (pos == 0 || isFirstInGroup(pos)) {
            outRect.top = mGroupHeight;
        }
    }

    @Override
    public void onDrawOver(Canvas c, RecyclerView parent, RecyclerView.State state) {
        super.onDrawOver(c, parent, state);
        //获取单条的数目
        int itemCount = state.getItemCount();
        int childCount = parent.getChildCount();
        //得出距离左边和右边的padding
        int right = parent.getWidth() - parent.getPaddingRight();
        //开始绘制
        String preGroupName;
        String currentGroupName = null;
        for (int i = 0; i < childCount; i++) {
            View child = parent.getChildAt(i);
            int position = parent.getChildAdapterPosition(child);
            preGroupName = currentGroupName;
            currentGroupName = getGroupName(position);
            if (currentGroupName == null || TextUtils.equals(currentGroupName, preGroupName)) {
                continue;
            }
            int viewBottom = child.getBottom();
            //top 决定当前顶部第一个悬浮Group的位置
            int top = Math.max(mGroupHeight, child.getTop());
            if (position + 1 < itemCount) {
                //获取下个GroupName
                String nextGroupName = getGroupName(position + 1);
                //下一组的第一个View接近头部
                if (!currentGroupName.equals(nextGroupName) && viewBottom < top) {
                    top = viewBottom;
                }
            }

            View headerView = getHeader(parent, position);
            headerView.buildDrawingCache();
            Bitmap bitmap = headerView.getDrawingCache();
            c.drawBitmap(bitmap, 0, top - mGroupHeight, null);

            //保存绘制的header的区域
            mHeaderRects.put(position, new Rect(child.getLeft(), top,
                    child.getLeft() + headerView.getWidth(), top + headerView.getHeight()));
        }
    }

    /**
     * 判断是不是组中的第一个位置
     * 根据前一个组名，判断当前是否为新的组
     */
    private boolean isFirstInGroup(int pos) {
        if (pos == 0) {
            return true;
        } else {
            String prevGroupId = getGroupName(pos - 1);
            String groupId = getGroupName(pos);
            return !TextUtils.equals(prevGroupId, groupId);
        }
    }

    /**
     * 获取组名
     *
     * @param position
     * @return 组名
     */
    private String getGroupName(int position) {
        if (mGroupListener != null) {
            return mGroupListener.getGroupName(position);
        } else {
            return null;
        }
    }

    /**
     * 获取组View
     *
     * @param position
     * @return 组名
     */
    private View getGroupView(int position) {
        if (mGroupListener != null) {
            return mGroupListener.getGroupView(position);
        } else {
            return null;
        }
    }

    public int findHeaderPositionUnder(int x, int y) {
        for (int i = 0; i < mHeaderRects.size(); i++) {
            Rect rect = mHeaderRects.get(mHeaderRects.keyAt(i));
            if (rect.contains(x, y)) {
                return mHeaderRects.keyAt(i);
            }
        }
        return -1;
    }

    /**
     * 获得自定义的Header
     *
     * @param parent
     * @param position
     * @return
     */
    public View getHeader(RecyclerView parent, int position) {
        int headerId = getGroupName(position).hashCode();
        View headerView = mHeaderViews.get(headerId);
        if (headerView == null) {
            //根据position获取View
            headerView = getGroupView(position);
            int right = parent.getWidth() - parent.getPaddingRight();

            ViewGroup.LayoutParams layoutParams = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, mGroupHeight);
            headerView.setLayoutParams(layoutParams);
            headerView.setDrawingCacheEnabled(true);
            headerView.measure(
                    View.MeasureSpec.makeMeasureSpec(parent.getWidth(), View.MeasureSpec.EXACTLY),
                    View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
            //指定高度、宽度的groupView
            headerView.layout(0, 0, right, mGroupHeight);
            mHeaderViews.put(headerId, headerView);
        }
        return headerView;
    }
}
